package com.kexio.enterprise.observability.metrics;

import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 业务指标组件
 * 
 * 提供业务相关指标的便捷收集方法
 * 
 * @author Kexio
 * @since 1.0.0
 */
@Component
public class BusinessMetrics {

    private final MetricsService metricsService;

    public BusinessMetrics(MetricsService metricsService) {
        this.metricsService = metricsService;
    }

    // ========== 用户相关指标 ==========

    /**
     * 记录用户登录
     * 
     * @param userId 用户ID
     * @param source 登录来源
     */
    public void recordUserLogin(Long userId, String source) {
        Map<String, String> tags = Map.of(
            "source", source,
            "userId", userId.toString()
        );
        metricsService.incrementCounter("business.user.login", tags);
    }

    /**
     * 记录用户登出
     * 
     * @param userId 用户ID
     * @param duration 会话时长（秒）
     */
    public void recordUserLogout(Long userId, long duration) {
        Map<String, String> tags = Map.of("userId", userId.toString());
        metricsService.incrementCounter("business.user.logout", tags);
        metricsService.recordTimer("business.user.session.duration", duration * 1000, tags);
    }

    /**
     * 记录用户注册
     * 
     * @param source 注册来源
     */
    public void recordUserRegistration(String source) {
        Map<String, String> tags = Map.of("source", source);
        metricsService.incrementCounter("business.user.registration", tags);
    }

    /**
     * 记录活跃用户
     * 
     * @param userId 用户ID
     */
    public void recordActiveUser(Long userId) {
        Map<String, String> tags = Map.of("userId", userId.toString());
        metricsService.incrementCounter("business.user.active", tags);
    }

    // ========== 订单相关指标 ==========

    /**
     * 记录订单创建
     * 
     * @param orderId 订单ID
     * @param amount 订单金额
     * @param currency 货币类型
     */
    public void recordOrderCreated(Long orderId, double amount, String currency) {
        Map<String, String> tags = Map.of(
            "orderId", orderId.toString(),
            "currency", currency
        );
        metricsService.incrementCounter("business.order.created", tags);
        metricsService.recordDistribution("business.order.amount", amount, tags);
    }

    /**
     * 记录订单支付
     * 
     * @param orderId 订单ID
     * @param amount 支付金额
     * @param paymentMethod 支付方式
     */
    public void recordOrderPaid(Long orderId, double amount, String paymentMethod) {
        Map<String, String> tags = Map.of(
            "orderId", orderId.toString(),
            "paymentMethod", paymentMethod
        );
        metricsService.incrementCounter("business.order.paid", tags);
        metricsService.recordDistribution("business.payment.amount", amount, tags);
    }

    /**
     * 记录订单取消
     * 
     * @param orderId 订单ID
     * @param reason 取消原因
     */
    public void recordOrderCancelled(Long orderId, String reason) {
        Map<String, String> tags = Map.of(
            "orderId", orderId.toString(),
            "reason", reason
        );
        metricsService.incrementCounter("business.order.cancelled", tags);
    }

    /**
     * 记录订单完成
     * 
     * @param orderId 订单ID
     * @param processingTime 处理时长（毫秒）
     */
    public void recordOrderCompleted(Long orderId, long processingTime) {
        Map<String, String> tags = Map.of("orderId", orderId.toString());
        metricsService.incrementCounter("business.order.completed", tags);
        metricsService.recordTimer("business.order.processing.time", processingTime, tags);
    }

    // ========== 产品相关指标 ==========

    /**
     * 记录产品浏览
     * 
     * @param productId 产品ID
     * @param category 产品类别
     */
    public void recordProductView(Long productId, String category) {
        Map<String, String> tags = Map.of(
            "productId", productId.toString(),
            "category", category
        );
        metricsService.incrementCounter("business.product.view", tags);
    }

    /**
     * 记录产品搜索
     * 
     * @param keyword 搜索关键词
     * @param resultCount 搜索结果数量
     */
    public void recordProductSearch(String keyword, int resultCount) {
        Map<String, String> tags = Map.of("keyword", keyword);
        metricsService.incrementCounter("business.product.search", tags);
        metricsService.recordGauge("business.product.search.results", resultCount, tags);
    }

    /**
     * 记录产品加入购物车
     * 
     * @param productId 产品ID
     * @param quantity 数量
     */
    public void recordProductAddedToCart(Long productId, int quantity) {
        Map<String, String> tags = Map.of("productId", productId.toString());
        metricsService.incrementCounter("business.product.cart.add", tags);
        metricsService.recordDistribution("business.product.cart.quantity", quantity, tags);
    }

    // ========== 内容相关指标 ==========

    /**
     * 记录文章阅读
     * 
     * @param articleId 文章ID
     * @param readTime 阅读时长（秒）
     */
    public void recordArticleRead(Long articleId, long readTime) {
        Map<String, String> tags = Map.of("articleId", articleId.toString());
        metricsService.incrementCounter("business.article.read", tags);
        metricsService.recordTimer("business.article.read.time", readTime * 1000, tags);
    }

    /**
     * 记录内容分享
     * 
     * @param contentId 内容ID
     * @param platform 分享平台
     */
    public void recordContentShare(Long contentId, String platform) {
        Map<String, String> tags = Map.of(
            "contentId", contentId.toString(),
            "platform", platform
        );
        metricsService.incrementCounter("business.content.share", tags);
    }

    /**
     * 记录评论发布
     * 
     * @param contentId 内容ID
     * @param userId 用户ID
     */
    public void recordCommentPosted(Long contentId, Long userId) {
        Map<String, String> tags = Map.of(
            "contentId", contentId.toString(),
            "userId", userId.toString()
        );
        metricsService.incrementCounter("business.comment.posted", tags);
    }

    // ========== 错误相关指标 ==========

    /**
     * 记录业务错误
     * 
     * @param errorType 错误类型
     * @param errorCode 错误代码
     * @param module 模块名称
     */
    public void recordBusinessError(String errorType, String errorCode, String module) {
        Map<String, String> tags = Map.of(
            "type", errorType,
            "code", errorCode,
            "module", module
        );
        metricsService.incrementCounter("business.error", tags);
    }

    /**
     * 记录API调用失败
     * 
     * @param apiName API名称
     * @param errorCode 错误代码
     */
    public void recordApiFailure(String apiName, String errorCode) {
        Map<String, String> tags = Map.of(
            "api", apiName,
            "errorCode", errorCode
        );
        metricsService.incrementCounter("business.api.failure", tags);
    }

    // ========== 资源相关指标 ==========

    /**
     * 记录文件上传
     * 
     * @param fileType 文件类型
     * @param fileSize 文件大小（字节）
     */
    public void recordFileUpload(String fileType, long fileSize) {
        Map<String, String> tags = Map.of("type", fileType);
        metricsService.incrementCounter("business.file.upload", tags);
        metricsService.recordDistribution("business.file.size", fileSize, tags);
    }

    /**
     * 记录文件下载
     * 
     * @param fileType 文件类型
     * @param fileSize 文件大小（字节）
     */
    public void recordFileDownload(String fileType, long fileSize) {
        Map<String, String> tags = Map.of("type", fileType);
        metricsService.incrementCounter("business.file.download", tags);
        metricsService.recordDistribution("business.file.download.size", fileSize, tags);
    }

    // ========== 性能相关指标 ==========

    /**
     * 记录数据库查询
     * 
     * @param queryType 查询类型
     * @param duration 查询时长（毫秒）
     */
    public void recordDatabaseQuery(String queryType, long duration) {
        Map<String, String> tags = Map.of("type", queryType);
        metricsService.incrementCounter("business.database.query", tags);
        metricsService.recordTimer("business.database.query.time", duration, tags);
    }

    /**
     * 记录缓存操作
     * 
     * @param operation 操作类型 (GET, PUT, DELETE)
     * @param cacheName 缓存名称
     * @param hit 是否命中
     */
    public void recordCacheOperation(String operation, String cacheName, boolean hit) {
        Map<String, String> tags = Map.of(
            "operation", operation,
            "cache", cacheName,
            "hit", String.valueOf(hit)
        );
        metricsService.incrementCounter("business.cache.operation", tags);
    }

    /**
     * 记录外部服务调用
     * 
     * @param serviceName 服务名称
     * @param duration 调用时长（毫秒）
     * @param success 是否成功
     */
    public void recordExternalServiceCall(String serviceName, long duration, boolean success) {
        Map<String, String> tags = Map.of(
            "service", serviceName,
            "success", String.valueOf(success)
        );
        metricsService.incrementCounter("business.external.service.call", tags);
        metricsService.recordTimer("business.external.service.duration", duration, tags);
    }

    // ========== 业务流程指标 ==========

    /**
     * 记录工作流开始
     * 
     * @param workflowName 工作流名称
     * @param workflowId 工作流ID
     */
    public void recordWorkflowStarted(String workflowName, String workflowId) {
        Map<String, String> tags = Map.of(
            "workflow", workflowName,
            "workflowId", workflowId
        );
        metricsService.incrementCounter("business.workflow.started", tags);
    }

    /**
     * 记录工作流完成
     * 
     * @param workflowName 工作流名称
     * @param workflowId 工作流ID
     * @param duration 执行时长（毫秒）
     * @param success 是否成功
     */
    public void recordWorkflowCompleted(String workflowName, String workflowId, 
                                       long duration, boolean success) {
        Map<String, String> tags = Map.of(
            "workflow", workflowName,
            "workflowId", workflowId,
            "success", String.valueOf(success)
        );
        metricsService.incrementCounter("business.workflow.completed", tags);
        metricsService.recordTimer("business.workflow.duration", duration, tags);
    }

    /**
     * 记录自定义业务事件
     * 
     * @param eventName 事件名称
     * @param tags 标签
     */
    public void recordCustomEvent(String eventName, Map<String, String> tags) {
        metricsService.incrementCounter("business.custom." + eventName, tags);
    }

    /**
     * 记录自定义业务指标
     * 
     * @param metricName 指标名称
     * @param value 指标值
     * @param tags 标签
     */
    public void recordCustomMetric(String metricName, double value, Map<String, String> tags) {
        metricsService.recordGauge("business.custom." + metricName, value, tags);
    }
}
